<template>
 <Cascader v-model="selValue" :data="list"  change-on-select filterable></Cascader>
</template>
<script>
export default {
	data:function(){
		return{		
			list:[],
			selValue:[]
		};
	},
	props:{
		value:{
			default:'0'
		},
		field:{
			default:'id'
		},
		is_update:{
			default:false
		},
		has_default:{
			default:1
		}
	},
	created:function(){
		this.load_data();
		this.init(this.value);
	},
	watch:{
		value(val){
			
			this.init(val);
		},
		selValue(val){
			
			this.$emit('input',val[val.length-1]);
		},
		is_update(val){
			if(val){
				this.load_data();
			}
		}
	},
	methods:{
		init(val){
			var self = this;
			if(val==''){
				return;
			}
			
			if(self.list.length==0){
				this.load_data(function(){
					self.selValue = [];
					
					for(var i=0;i<self.list.length;i++){
						var arr = [];
						var result = self.get_child_leven(self.list[i],val,arr);
						if(result){
							arr.unshift(self.list[i].value);
							self.selValue = arr;
							break;
						}
					}
				});
			}
			else{
				self.selValue = [];
				
				for(var i=0;i<self.list.length;i++){
					var arr = [];
					var result = self.get_child_leven(self.list[i],val,arr);
					if(result){
						arr.unshift(self.list[i].value);
						self.selValue = arr;
						break;
					}
				}
			}
			
		},
		get_child_leven(item,val,arr){
			
			
			if(item.value==val){
				return true;
			}
			
			if(typeof(item.children)!='object'){
				return false;
			}
			var list = item.children;
			
			for(var i=0;i<list.length;i++){
				var result = this.get_child_leven(list[i],val,arr);
				if(result){
					arr.unshift(list[i].value)
					return true;
				}
			}
			
			return false;
		},
		load_data(call){
			var self = this;
			var postdata = {
				is_filter:this.is_update?1:0
			};
			
			Whttp.load('User/Bumen/get_all',postdata,function(result){
				var arr = [];
				
				if(self.has_default){
					arr.push({value:'',label:'不选择'});
				}
				
				var children = self.get_child(result);
				for(var i=0;i<children.length;i++){
					arr.push(children[i]);
				}
				
				self.list = arr;
				typeof(call)=='function' && call();
			});
		},
		get_child(ls_list){
			var self = this;
			var childrens = [];
			if(typeof(ls_list)!='object'){
				return childrens;
			}
			
			for(var j=0;j<ls_list.length;j++){
			
				var data = {
					value: ls_list[j][self.field],
					label: ls_list[j].name
				};
				if(typeof(ls_list[j].children)=='object'){
					data['children'] = this.get_child(ls_list[j].children);
				}
				childrens.push(data);
			}
			
			return childrens;
		}
	}
}
</script>
<style scoped>

</style>